<?php
namespace app\admin\controller;

use think\Db;
use think\Loader;
use think\Request;

class Manageuser extends Admin
{
    /*
     * 管理员列表
     * */
    public function index()
    {
        $keyword = input('keyword', '', 'op_t');
        $map = array();
        if ($keyword) {
            $map['admin_username'] = ['like', '%' . $keyword . '%'];
        }
        // 并且每页显示10条数据
        $list = Db::name('Admin')->where($map)->paginate(10);
        $page = $list->render();
        $data = $list->toArray();
        foreach ($data['data'] as $key => &$val) {
            $val['group_name'] = '';
            $group_id = db('AuthGroupAccess')->where('uid', $val['id'])->value('group_id');
            if ($group_id) {
                $val['group_name'] = db('AuthGroup')->where('id', $group_id)->value('title');
            }
        }
        $data['keyword'] = $keyword;
        $this->assign($data);
        $this->assign('page', $page);
        return $this->fetch('admin_list');
    }

    /*
     * 添加管理员
     * */
    public function AdminAdd()
    {
        if (Request::instance()->isPOST()) {
            $validate = Loader::validate('Admin');
            $data = $_POST;
            $res = $validate->scene('add')->check($data);
            if (!$res) {
                $this->error($validate->getError());
            }
            $group_id = $data['group_id'];
            unset($data['group_id']);
            $data['admin_addtime'] = time();
            $data['admin_pwd'] = md5_password($data['admin_pwd']);
            // 启动事务
            Db::startTrans();
            try {
                $uid = Db::name('Admin')->insertGetId($data);
                $access = Db::name('AuthGroupAccess')->insert(['uid' => $uid, 'group_id' => $group_id]);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
            if ($uid && $access) {
                $this->success('操作成功', 'Manageuser/AdminList');
            } else {
                $this->error('操作失败');
            }
        }
        $data['group'] = Db::name('AuthGroup')->where('status','1')->field('id,title')->select();
        $this->assign($data);
        return $this->fetch('admin_add');
    }

    /*
     * 编辑管理员
     * */
    public function AdminEdit()
    {
        $id = input('id', '', 'intval');
        $data['row'] = Db::name('Admin')->where('id', $id)->alias('a')->join('auth_group_access b', 'a.id=b.uid', 'LEFT OUTER')->find();
        if (!$data['row']) {
            $this->error('操作有误');
        }
        if (Request::instance()->isPOST()) {
            $data = input('post.');
            $data['status']=isset($data['status'])?$data['status']:0;
            if (model('Admin')->checkName($data['id'], $data['admin_username'])) {
                $this->error('用户名已存在');
            }
            $validate = Loader::validate('Admin');
            if (!$validate->scene('edit')->check($data)) {
                $this->error($validate->getError());
            }
            if ($data['admin_pwd']) {
                if (!$validate->scene('pass')->check($data)) {
                    $this->error($validate->getError());
                }
                $data['admin_pwd'] = md5_password($data['admin_pwd']);
            }else{
                unset($data['admin_pwd']);
            }
            $group_id = $data['group_id'];
            $flag = Db::name('AuthGroupAccess')->where('uid', $id)->update(['group_id' => $group_id]);
            unset($data['group_id']);
            if (Db::name('Admin')->update($data) || $flag) {
                $this->success('操作成功', url('Manageuser/AdminEdit', array('id' => $id)));
            } else {
                $this->error('操作失败');
            }
        }
        $data['group'] = Db::name('AuthGroup')->where('status','1')->field('id,title')->select();
        $this->assign($data);
        return $this->fetch('admin_edit');
    }

    /*
     * 设置管理员状态
     * */
    public function AdminState()
    {
        $id = input('post.id', '', 'intval');
        if (empty($id)) {
            $this->error('操作有误!');
        }
        $status = Db::name('Admin')->where('id', $id)->value('status');
        $status = $status ? 0 : 1;
        $flag = Db::name('Admin')->where('id', $id)->update(['status' => $status]);
        if ($flag) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /*
     * 删除管理员
     * */
    public function AdminDel()
    {
        $id = input('post.id', '', 'intval');
        if (empty($id) || $id == 1) {
            $this->error('操作有误!');
        }
        if ($id == is_login()) {
            $this->error('不能删除本人账号');
        }
        $flag = Db::name('Admin')->delete($id);
        Db::name('AuthGroupAccess')->where('uid', $id)->delete();
        if ($flag) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }
}
